package com.sanji.sjmallmodule.order;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.account.RedPackageBean;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.BottomPopWindow;
import com.sanji.sjmallwidget.MyListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/***
 * 确认订单
 ***/
public class FirmOrderActivity extends BaseActivity implements View.OnClickListener, NoHttpListener {

    private static final int WHAT_ORDER_PUSH = ConfigAPI.ORDER_PUSH_URL.hashCode();

    @BindView(R.id.common_back_img)
    ImageView mCommonBackImg;
    @BindView(R.id.common_left_tv)
    TextView mCommonLeftTv;
    @BindView(R.id.firm_order_scrollview)
    ScrollView mFirmOrderScrollView;
    @BindView(R.id.firm_order_receiver_name_tv)
    TextView mFirmOrderReceiverNameTv;
    @BindView(R.id.firm_order_address_tv)
    TextView mFirmOrderAddressTv;
    @BindView(R.id.firm_order_receiver_phone_tv)
    TextView mFirmOrderReceiverPhoneTv;
    @BindView(R.id.firm_order_contact_phone_tv)
    TextView mFirmOrderContactPhoneTv;
    @BindView(R.id.firm_order_submit_btn)
    TextView mFirmOrderSubmitBtn;
    @BindView(R.id.firm_order_coust_tv)
    TextView mFirmOrderCoustTv;
    //收货地址详情
    @BindView(R.id.firm_order_address_dest_layout)
    RelativeLayout mFirmOrderAddressDestLayout;
    //添加地址
    @BindView(R.id.firm_order_add_address_tv)
    TextView mAddAddress;
    @BindView(R.id.firm_order_listview)
    MyListView mFirmOrderListview;
    //使用红包
    @BindView(R.id.firm_order_red_pack_arrow)
    ImageView mFirmOrderRedPackArrow;
    @BindView(R.id.firm_order_red_pack_title)
    LinearLayout mFirmOrderRedPackTitle;
    @BindView(R.id.firm_order_red_pack_layout)
    LinearLayout mFirmOrderRedPackLayout;
    //运费详情
    @BindView(R.id.firm_order_fare_title_layout)
    LinearLayout mFirmOrderFareTitle;
    @BindView(R.id.firm_order_fare_arrow)
    ImageView mFirmOrderFareArrow;
    @BindView(R.id.firm_order_fare_layout)
    LinearLayout mFirmOrderFareLayout;
    @BindView(R.id.firm_order_fare_toast)
    TextView mFirmFareToast;
    //总额
    @BindView(R.id.firm_order_result_coust_value)
    TextView mFirmOrderResultCoustValue;
    //红包
    @BindView(R.id.firm_order_result_red_pack_value)
    TextView mFirmOrderResultRedPackValue;
    //运费
    @BindView(R.id.firm_order_result_fare_value)
    TextView mFirmOrderResultFareValue;

    RelativeLayout mPopPaymengOnling;
    CheckBox mPopPaymengOfflineCb;
    TextView mPopPaymentCoast;
    Button mPopPaymentSubmit;

    private boolean isShowRedPackage = false;
    private boolean isShowfare = false;
    //商品集合
    private List<ShopcarChildBean> shopChildList = new ArrayList<>();

    private FirmOrderAdapter mFirmOrderAdapter;

    //红包数据
    private List<RedPackageBean> redPackageList = new ArrayList<>();
    private List<CheckBox> cbList = new ArrayList<>();

    //总额
    private double amount = 188.0;
    //红包
    private double redPackagePrice = 0.0;
    //运费
    private double fare = 0.0;
    //实付金额
    private double actualAmount = 0.0;

    private BottomPopWindow payPopLayout;
    private String addressStr;//收货地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firm_order);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        shopChildList = (List<ShopcarChildBean>) bundle.getSerializable("list");
        amount = bundle.getDouble("amount");

        initView();
    }


    private void initView() {
        mCommonBackImg.setVisibility(View.VISIBLE);
        mCommonBackImg.setOnClickListener(this);
        mCommonLeftTv.setVisibility(View.VISIBLE);
        mCommonLeftTv.setText(getResources().getString(R.string.confirm_order));
        mCommonLeftTv.setOnClickListener(this);
        mFirmOrderContactPhoneTv.setOnClickListener(this);
        mAddAddress.setOnClickListener(this);
        mFirmOrderRedPackTitle.setOnClickListener(this);
        mFirmOrderFareTitle.setOnClickListener(this);
        mFirmOrderSubmitBtn.setOnClickListener(this);
        addressStr = myShare.getString(ConfigConts.ADDRESS_STR, null);
        if (null != addressStr) {
            mFirmOrderAddressDestLayout.setVisibility(View.VISIBLE);
            mAddAddress.setVisibility(View.GONE);

            mFirmOrderReceiverNameTv.setText(myShare.getString(ConfigConts.TRUE_NAME, null));
            mFirmOrderReceiverPhoneTv.setText(myShare.getString(ConfigConts.MOBILE, null));
            mFirmOrderAddressTv.setText(myShare.getString(ConfigConts.REGION, null) + "  " + myShare.getString(ConfigConts.ADDRESS_STR, null));
        }
        initData();
    }


    private void initData() {

        //设置红包数据
//        initRedPackageData();
        //计算商品总额

        //设置运费提醒
        int partsFre = myShare.getInt(ConfigConts.FARE_PARTS_PRICE, 0);
        String fareStr = getResources().getString(R.string.confirm_fare_toast);
        String fareToast = String.format(fareStr,myShare.getInt(ConfigConts.FARE_PHONE_NUM, 1),partsFre);
        mFirmFareToast.setText(fareToast);

        int phoneNum = 0;
        double partsTotal = 0;
        for (ShopcarChildBean bean : shopChildList) {
            if (getResources().getString(R.string.phone).equals(bean.getGroupTitle())) {
                phoneNum++;
            } else {
                partsTotal += bean.getSubTotal();
            }
        }

        if (phoneNum >= myShare.getInt(ConfigConts.FARE_PHONE_NUM, 1) || partsTotal >= partsFre) {
            fare = 0;
        } else {
            fare = myShare.getInt(ConfigConts.FARE_COST, 0);
        }
        String priceTitle = getResources().getString(R.string.price_title);
        mFirmOrderResultCoustValue.setText(priceTitle + amount);
        mFirmOrderResultRedPackValue.setText(priceTitle + redPackagePrice);
        mFirmOrderResultFareValue.setText(priceTitle + fare);

        getActualAmount();

        mFirmOrderAdapter = new FirmOrderAdapter(this, shopChildList);
        mFirmOrderListview.setAdapter(mFirmOrderAdapter);

        //设置scrollview置顶
        mFirmOrderScrollView.smoothScrollTo(0, 0);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
                finish();
            case R.id.common_left_tv:
                finishActivity();
                break;
            case R.id.firm_order_contact_phone_tv:
                Tools.dialPhone(this, mFirmOrderContactPhoneTv.getText().toString());
                break;
            case R.id.firm_order_add_address_tv:
                //新建收货地址
                Intent reverIntent = new Intent(this, NewReverAddressActivity.class);
                startActivityForResult(reverIntent, 0);
                break;
            case R.id.firm_order_red_pack_title:
                //使用红包
                if (isShowRedPackage) {
                    //闭
                    mFirmOrderRedPackLayout.setVisibility(View.GONE);
                    mFirmOrderRedPackArrow.setImageResource(R.mipmap.select_down);
                    isShowRedPackage = false;
                } else {
                    //开
                    mFirmOrderRedPackLayout.setVisibility(View.VISIBLE);
                    mFirmOrderRedPackArrow.setImageResource(R.mipmap.select_up);
                    isShowRedPackage = true;
                }
                break;
            case R.id.firm_order_fare_title_layout:
                //运费详情
                if (isShowfare) {
                    //闭
                    mFirmOrderFareLayout.setVisibility(View.GONE);
                    mFirmOrderFareArrow.setImageResource(R.mipmap.select_down);
                    isShowfare = false;
                } else {
                    //开
                    mFirmOrderFareLayout.setVisibility(View.VISIBLE);
                    mFirmOrderFareArrow.setImageResource(R.mipmap.select_up);
                    isShowfare = true;
                }
                break;
            case R.id.firm_order_submit_btn:
                //提交订单
                try {
                    JSONObject json = new JSONObject();
                    json.put("userId", myShare.getString(ConfigConts.USER_ID, ""));
                    JSONArray catrIds = new JSONArray();
                    for (ShopcarChildBean bean : shopChildList) {
                        catrIds.put(bean.getCartId());
                    }
                    json.put("cartIds", catrIds);

                    Request<JSONObject> orderPushRequest = NoHttp.createJsonObjectRequest(ConfigAPI.ORDER_PUSH_URL, RequestMethod.POST);
                    orderPushRequest.setDefineRequestBodyForJson(json);
                    NoHttpCallBack.getInstance().add(this, ConfigAPI.ORDER_PUSH_URL.hashCode(), orderPushRequest, this, true, true);

                } catch (Exception e) {
                    e.printStackTrace();
                }


                break;
        }
    }


    /**
     * 设置红包数据
     */
    private void initRedPackageData() {

        RedPackageBean bean1 = new RedPackageBean(5.0);
        RedPackageBean bean2 = new RedPackageBean(10.0);
        redPackageList.add(bean1);
        redPackageList.add(bean2);
        mFirmOrderRedPackLayout.removeAllViews();
        for (int i = 0; i < redPackageList.size(); i++) {
            RedPackageBean bean = redPackageList.get(i);
            View view = LayoutInflater.from(this).inflate(R.layout.item_red_package, null);
            TextView priceTv = (TextView) view.findViewById(R.id.red_package_item_price_tv);
            priceTv.setText(bean.getPrice() + getResources().getString(R.string.price_unit));
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.red_package_item_cb);
            checkBox.setOnClickListener(new RedPackageClick(i));
            mFirmOrderRedPackLayout.addView(view);
            checkBox.setChecked(bean.isChecked());
            cbList.add(checkBox);
        }


    }

    @Override
    public void onSuccessed(int what, Response response) {
        try {
            JSONObject respJson = new JSONObject(response.get().toString());
            String status = respJson.optString("status");
            if (ConfigConts.STATUS_SUCCESS.equals(status)) {
                if (what == WHAT_ORDER_PUSH) {
                    Tools.toastTools(mCtx, getResources().getString(R.string.request_success));
                    JSONObject result = respJson.optJSONObject("result");
                    String orderId = result.optString("orderId");
                    myShare.put(ConfigConts.IsRefresh, true);
                    Intent intent = new Intent(this, OrderPayActivity.class);
                    intent.putExtra("actualAmount", actualAmount);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                    finishActivity();
                }
            } else {
                String errMsg = respJson.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(mCtx, errMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(mCtx, getResources().getString(R.string.request_false));
    }


    /**
     * 红包选择
     */
    class RedPackageClick implements View.OnClickListener {
        private int pos;

        RedPackageClick(int p) {
            this.pos = p;
        }

        @Override
        public void onClick(View view) {
            RedPackageBean bean;
            for (int i = 0; i < redPackageList.size(); i++) {
                bean = redPackageList.get(i);
                if (pos == i) {
                    boolean flag = !bean.isChecked();
                    bean.setChecked(flag);
                    cbList.get(i).setChecked(flag);
                    if (flag) {
                        redPackagePrice = redPackageList.get(pos).getPrice();
                    } else {
                        redPackagePrice = 0.0;
                    }

                    mFirmOrderResultRedPackValue.setText("-" + getResources().getString(R.string.price_title) + redPackagePrice);
                    getActualAmount();
                } else {
                    bean.setChecked(false);
                    cbList.get(i).setChecked(false);
                }
            }

        }
    }

    /**
     * 计算实付金额
     */
    private void getActualAmount() {
        actualAmount = Tools.subtract(amount, redPackagePrice);
        actualAmount = Tools.add(actualAmount, fare);
        mFirmOrderCoustTv.setText(getResources().getString(R.string.price_title) + actualAmount);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {

                    Bundle bundle = data.getExtras();
                    String rever = bundle.getString("rever");
                    String phone = bundle.getString("phone");
                    String zone = bundle.getString("zone");
                    String dest = bundle.getString("dest");

                    mFirmOrderAddressDestLayout.setVisibility(View.VISIBLE);
                    mAddAddress.setVisibility(View.GONE);

                    mFirmOrderReceiverNameTv.setText(rever);
                    mFirmOrderReceiverPhoneTv.setText(phone);
                    mFirmOrderAddressTv.setText(zone + " " + dest);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
